<template>
    <el-dialog :title="operated === 'add' ? '添加学员' : '删除学员'" v-model="dialogVisible" width="90%" append-to-body
        :close-on-click-modal="false">
        <div class="sorce-container">
            <el-form ref="queryRef" :model="queryParams" inline label-width="auto">
                <el-form-item label="学生姓名" prop="stuName">
                    <el-input v-model="queryParams.stuName" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item label="手机号" prop="phoneNumber">
                    <el-input v-model="queryParams.phoneNumber" placeholder="请输入" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleRequireStudents">查 询</el-button>
                    <el-button icon="Refresh" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
            <el-table ref="tableRef" v-loading="loading" :data="studentList" @select="handleTableSelect"
                @selectAll="handleTableSelectAll" height="500">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="序号" width="55" align="center" type="index" />
                <el-table-column label="学生姓名" align="center" prop="stuName" />
                <el-table-column label="手机号" align="center" prop="phoneNumber" />
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="handleRequireStudents" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit">提 交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ElMessageBox, ElMessage } from "element-plus";
import {
    selectStuList,
    addClassStu
} from "@/api/exam/classz";
import { nextTick, reactive } from "vue";
const emits = defineEmits(["update:visible", "finish"]);
const props = defineProps({
    visible: {
        type: Boolean,
        default: false,
    },
    classId: {
        type: Number,
        default: null,
    },
    operated: {
        type: String,
        default: 'add',
    },
});
//
const dialogVisible = computed({
    get: () => {
        return props.visible;
    },
    set: (value) => {
        emits("update:visible", value);
    },
});
const { proxy } = getCurrentInstance();
const loading = ref(false);
const total = ref(0);
const tableRef = ref(null)
const queryParams = reactive({
    classId: null,
    stuName: null,
    phoneNumber: null,
    operated: 'add',
    pageNum: 1,
    pageSize: 10,
});
const studentList = ref([])
const selectList = ref([])
watch(
    () => props.visible,
    (value) => {
        if (!value) {
            studentList.value = []
            selectList.value = []
            queryParams.classId = null
            queryParams.pageNum = 1
            queryParams.pageSize = 10
            queryParams.stuName = null,
        queryParams.phoneNumber = null,
        proxy.resetForm("queryRef");

        } else {
            queryParams.classId = props.classId
            queryParams.operated = props.operated
            handleRequireStudents()
        }
    }
);

const handleTableSelect = (select, row) => {
    const index = selectList.value.findIndex(i => i.stuId === row.stuId)
    if (index > -1) {
        selectList.value.splice(index, 1)
    } else {
        selectList.value.push(row)
    }
}
const handleTableSelectAll = (selects) => {
    if (selects.length > 0) {
        selects.forEach(item => {
            const index = selectList.value.findIndex(i => i.stuId === item.stuId)
            if (index < 0) {
                selectList.value.push(item)
            }
        })
    } else {
        studentList.value.forEach(item => {
            const index = selectList.value.findIndex(i => i.stuId === item.stuId)
            if (index > -1) {
                selectList.value.splice(index, 1)
            }
        })
    }
}
// 列表数据请求
const handleRequireStudents = async () => {
    try {
        loading.value = true;
        const res = await selectStuList(queryParams)
        loading.value = false;
        if (res.code === 200) {
            studentList.value = res.rows
            total.value = res.total;
            nextTick(() => {
                if (selectList.value.length === 0) {
                    return
                }
                selectList.value.forEach(item => {
                    const index = studentList.value.findIndex(i => i.stuId === item.stuId)
                    if (index > -1) {
                        console.log("🚀 ~ handleRequireStudents ~ item:", item)
                        tableRef.value.toggleRowSelection(studentList.value[index], true)
                    }
                })
            })
        }
    } catch (error) {
        loading.value = false;
    }

}
// 提交
const handleSubmit = () => {
    console.log(selectList.value)
    if (selectList.value.length === 0) {
        ElMessage.warning('请选择需要操作得数据')
        return
    }

    const optionTitle = props.operated === 'add' ? '添加' : '删除'
    ElMessageBox.confirm(`是否确认${optionTitle}选中学员`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            requireSubmit();
        })
        .catch(() => { });
};
const requireSubmit = async () => {
    try {
        const params = {
            classId: props.classId,
            operated: props.operated,
            stuList: selectList.value.map(i => i.stuId)
        }
        const res = await addClassStu(params);
        if (res.code === 200) {
            proxy.$modal.msgSuccess("操作成功");
            dialogVisible.value = false
            emits('finish')
        }
    } catch (error) { }
};
/** 表单重置 */
function reset() {
    queryParams.stuName = null,
        queryParams.phoneNumber = null,
        proxy.resetForm("queryRef");
    handleRequireStudents()
}
</script>
<style lang="scss" scoped>
.sorce-container {
    height: 600px;
}
</style>